package com.baijiayun.liveuibase.widgets.webview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.baijiayun.liveuibase.R;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

public class ControllerWebView extends FrameLayout {
    private TextView tvComplete;
    private TextView tvUrl;
    private ImageView ivRefresh;
    private WebView mWebView;
    private ImageView ivBack;
    private ImageView ivForward;

    private IOnOptListener mOnOptListener;

    public ControllerWebView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public ControllerWebView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.uibase_controller_webview, this);
        tvComplete = findViewById(R.id.uibase_controller_webview_complete);
        tvUrl = findViewById(R.id.uibase_controller_webview_url);
        ivRefresh = findViewById(R.id.uibase_controller_webview_refresh);
        mWebView = findViewById(R.id.uibase_controller_webview_main);
        ivBack = findViewById(R.id.uibase_controller_webview_opt_back);
        ivForward = findViewById(R.id.uibase_controller_webview_opt_forward);

        this.setVerticalScrollBarEnabled(false);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        mWebView.getSettings().setAppCacheEnabled(false);
        mWebView.getSettings().setDatabaseEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        initWebView();

        tvComplete.setOnClickListener(v -> {
            mWebView.clearHistory();
            if (mOnOptListener != null) {
                mOnOptListener.onComplete();
            }
        });

        ivRefresh.setOnClickListener(v -> mWebView.reload());
        ivBack.setOnClickListener(v -> {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
            }
        });
        ivForward.setOnClickListener(v -> {
            if (mWebView.canGoForward()) {
                mWebView.goForward();
            }
        });
    }

    private void initWebView() {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if( url.startsWith("http:") || url.startsWith("https:") ) {
                    view.loadUrl(url);
                    tvUrl.setText(url);
                    return false;
                }
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    ControllerWebView.this.getContext().startActivity(intent);
                } catch (Exception ignore) {
                    // do nothing
                }
                return true;
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                sslErrorHandler.proceed();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                ivBack.setEnabled(mWebView.canGoBack());
                ivForward.setEnabled(mWebView.canGoForward());
            }
        });
    }

    public void resetUrl(String url) {
        // 清空视图及缓存
        mWebView.clearHistory();
        mWebView.clearCache(true);
        mWebView.clearFormData();

        ivBack.setEnabled(false);
        ivForward.setEnabled(false);

        mWebView.loadUrl(url);
    }

    public void setOnOptListener(IOnOptListener mOnOptListener) {
        this.mOnOptListener = mOnOptListener;
    }

    public interface IOnOptListener {
        void onComplete();
    }
}
